<template>
  <a-modal  :visible="show" title="新增素材" @ok="materialConfirm" cancelText="关闭" class="pop-table"
           :closable="false" @cancel="handleCancel">
           <a-form style='margin:30px 0'>
        <a-form-item v-show='queryParam.materialType == 1' :labelCol='labelCol' :wrapperCol='wrapperCol'
                     label='图片上传'>
          <j-image-upload accept='image/*' ref='imageUp' v-model='requestParam.materialUrl' @change='imgChange'
                          @beforeUpload='beforeUpload' :beforeflag='true' :is-multiple='true'></j-image-upload>
        </a-form-item>
        <a-form-item v-show='queryParam.materialType == 2' :labelCol='labelCol' :wrapperCol='wrapperCol'
                     label='视频上传'>
          <j-upload accept='video/*' v-model='requestParam.materialUrl' @change='fileChange'></j-upload>
        </a-form-item>
        <a-form-item v-show='queryParam.materialType == 3' :labelCol='labelCol' :wrapperCol='wrapperCol'
                     label='音频上传'>
          <j-upload accept='audio/*' v-model='requestParam.materialUrl' @change='fileChange'></j-upload>
        </a-form-item>
        <a-form-item v-show='queryParam.materialType == 2' :labelCol='labelCol' :wrapperCol='wrapperCol'
                     label='输入素材封面'>
          <j-upload ref='imageUp' v-model='requestParam.materialCoverUrl' @change='coverChange'></j-upload>
        </a-form-item>
        <a-form-item v-show='queryParam.materialType == 1' :labelCol='labelCol' :wrapperCol='wrapperCol'
                     label='图片标题'>
          <a-input placeholder='输入图片标题' v-model='requestParam.materialName' />
        </a-form-item>
        <a-form-item v-show='queryParam.materialType != 1' :labelCol='labelCol' :wrapperCol='wrapperCol'
                     label='输入素材标题'>
          <a-input placeholder='输入素材标题' v-model='requestParam.remark' />
        </a-form-item>
        <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='输入标签'>
          <a-input placeholder='输入标签' v-model='requestParam.keyword' />
        </a-form-item>
        <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属分组'>
<!--          <a-select v-model='requestParam.groupId' placeholder='请选择标签' :default-value='1' class='select-box'>-->
<!--            <a-select-option v-for='(item,index) of groupList' :key='index' :value='item.groupId'>{{ item.groupName }}-->
<!--            </a-select-option>-->
<!--          </a-select>-->
          <a-tree-select
            v-model="requestParam.groupId"
            :tree-data="treeData"
            :replaceFields="{children:'crdFileBliList',key:'id',title:'fileName',value:'id'}"
            allow-clear></a-tree-select>
        </a-form-item>
        <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='选择权限'>
          <a-tree-select
            v-model='requestParam.depart'
            :tree-data='departTreeData'
            tree-checkable
            search-placeholder='选择权限'
          />
        </a-form-item>
      </a-form>
  </a-modal>
</template>

<script>
//新增素材弹窗表单
import { getAction, postAction,httpAction } from '@/api/manage'
import { queryDepartTreeList } from '@/api/api'

export default {
  name: 'MaterialFormModal',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    materialType: {
      type: Number,
      default: 1
    }
  },
  watch: {
    show(newValue) {
      // 当localValue变化时，可以执行其他逻辑，例如更新父组件的状态
      this.$emit('update:visible', newValue);
    },
    materialType: {
      handler(newValue) {
        this.queryParam.materialType = newValue; // 同步父组件传递的最新值
      },
      immediate: true, // 初始渲染时立即执行一次
    },
  },
  data() {
    return {
      title:"操作",
        show: this.visible,
        materialModal: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules:{
        },
        url: {
          add: "/materia/crdMaterialInfo/add",
          edit: "/materia/crdMaterialInfo/edit",
        },
        queryParam:{
          materialType:1
        },
        requestParam: {
          materialType: 1,
          groupId: '',
          materialName: '',
          materialUrl: '',
          materialCoverUrl: '',
          remark: '',
          depart: []
        },
        groupList:[],
        cropperVisible: false,
        options: {
          img: '',
          autoCrop: true,
          autoCropWidth: 200,
          autoCropHeight: 200,
          fixedBox: false
        },
        departTreeData: [],
        treeData: [],
      }

  },
  created() {
    this.getGroupList()
    this.loadTree()
    this.queryFileClassify()
  },
  methods: {
    async queryFileClassify() {
      const params = {fileGroupType: 0};
      const res = await getAction('filebank/api/queryFileGroupAndFolder', params);
      if (res && res.success) {
        this.treeData  = res.result;
      }
    },
    loadTree() {
      this.departTreeData = []
      queryDepartTreeList().then((res) => {
        if (res.success) {
          for (let i = 0; i < res.result.length; i++) {
            let temp = res.result[i]
            this.departTreeData.push(temp)
          }
        }
      })
    },

    materialNameConfirm() {
      let groupNames = this.groupList.filter(item => item.groupId === this.changeChange.groupId)
      postAction('/materia/crdMaterialInfo/editName', {
        id: this.editMaterial.id,
        materialName: this.materialName,
        groupId: this.changeChange.groupId,
        groupName: (groupNames && groupNames.length > 0) ? groupNames[0].groupName : ''
      }).then(res => {
        this.materialNameModal = false
        this.$message.success('修改成功')
        this.loadData()
        this.getGroupList()
      })
    },

    editName(item) {
      console.log(item)
      this.materialNameModal = true
      this.materialName = item.materialName
      this.editMaterial = item
    },
    imgChange(path, item) {
      console.log(item)
      this.requestParam.materialUrl = path
      this.requestParam.materialList = item.fileList
      this.requestParam.materialName = ''
      item.fileList.forEach(file => {

        this.requestParam.materialName += file.name + ', '
      })
    },
    fileChange(item) {
      this.requestParam.materialUrl = item.file.response.result.url
    },
    add () {
        this.edit({});
      },
      edit (record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'remark','delFlag','materialType','keyword','groupId','groupName','materialName','materialUrl'))
		  //时间格式化
        });

      },
      getGroupList() {
        //分组信息
        getAction('materia/crdMaterialInfo/queryGroupInfo', {
          materialType: 1
        }).then(res => {
          this.groupList = res.result
        })
      },
      close () {
        this.$emit('ok');
        this.show = false;
      },
      coverChange(path, item) {
        this.requestParam.materialCoverUrl = item.file.response.result.url
      },

      fileChange(item) {
        this.requestParam.materialUrl = item.file.response.result.url
      },
      beforeUpload(file, resolve) {
      console.log(file)
      this.options.img = window.URL.createObjectURL(file)
      this.cropperVisible = true
      this.resolve = resolve
    },
      handleOk () {

        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            //时间格式化

            console.log(formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })



          }
        })
      },
      handleCancel () {
        this.close()
      },
      materialConfirm() {
      console.log(this.requestParam.depart)
      this.requestParam.materialType = this.queryParam.materialType
      // this.requestParam.groupId = this.queryParam.groupId;
      // if (!this.requestParam.keyword) {
      //   this.$message.warning('请输入标签')
      //   return false
      // }
      console.log(this.requestParam)
      if (!this.requestParam.groupId) {
        this.$message.warning('请选择有效分组')
        return false
      }
      if (!this.requestParam.materialUrl) {
        this.$message.warning('请上传素材')
        return false
      }
      if (this.requestParam.materialList && this.requestParam.materialList.length > 0) {
        let httpList = []
        this.requestParam.materialList.forEach(material => {
          let param = { ...this.requestParam }
          param.materialName = material.name
          param.materialUrl = material.url
          delete param.materialList
          httpList.push(httpAction('materia/crdMaterialInfo/add', param, 'post'))
        })
        Promise.all(httpList).then(res => {
          this.addMaterialSuccess()
        })
      } else {
        httpAction('materia/crdMaterialInfo/add', this.requestParam, 'post').then(res => {
          this.addMaterialSuccess()
        })
      }

    },
    addMaterialSuccess() {

      this.requestParam = {
        materialType: this.queryParam.materialType,
        groupId: '',
        materialName: '',
        materialUrl: '',
        materialCoverUrl: '',
        remark: '',
        depart: this.requestParam.depart
      }
      this.$emit('refresh')
      this.$emit('ok')
      this.show = false

      this.getGroupList()
    },
  }
}
</script>

<style scoped>

</style>